<?php

namespace app\common\service\ProviderService;

use app\model\BbcModel\Goods;
use app\model\BbcModel\GoodsBrand;
use app\model\BbcModel\GoodsClass;
use think\facade\Db;
use app\Normal;
use app\model\BbcModel\ServiceProvider;
use app\model\BbcModel\ServiceLevel;
use app\model\BbcModel\Channel;
use app\model\BbcModel\ChannelWx;
use app\model\BbcModel\Host;
use app\model\BbcModel\Manager;
use app\model\BbcModel\AuthGroup;
use app\model\BbcModel\ChannelBusiness;
use app\model\BbcModel\Order;



/**
 * 服务商业务
 * @author linan
 */
class ServiceProviderService
{


    /**
     * 新增大B
     * @param array $param
     * @return array
     */
    public function addChannel(array $param)
    {
        if(empty(trim($param['business_name']))){
            return Normal::returnCode(Normal::FAIL,"请输入大B名称");
        }
        $notify=Host::instance()->info(['tob'=>'notify','status'=>1]);
        $add_data['notify_url']=!empty($notify)?$notify['host'].'/master/SyncApi/receiveGoods/':'';
        $has=Channel::instance()->info(['business_name'=>$param['business_name']]);
        if($has){
            return Normal::returnCode(Normal::SUC,"请求成功",['cid'=>$has['id'], 'notify_url'=>$add_data['notify_url'].$has['id']]);
        }
        if(empty(trim($param['mobile']))){
            return Normal::returnCode(Normal::FAIL,"请输入大B联系方式");
        }
        if(empty(trim($param['account']))){
            return Normal::returnCode(Normal::FAIL,"请输入大B账号");
        }
        $use=Manager::instance()->info(['account'=>$param['account']]);
        if($use && empty($param['id'])){
            return Normal::returnCode(Normal::FAIL,"大B账号已存在");
        }
        if($use && !empty($param['id']) && $use['id']<>$param['id']){
            return Normal::returnCode(Normal::FAIL,"大B账号已存在");
        }
        if(empty(trim($param['pass']))){
            return Normal::returnCode(Normal::FAIL,"请输入大B密码");
        }
        if(empty(trim($param['name']))){
            return Normal::returnCode(Normal::FAIL,"请输入大B名字");
        }
        if(empty(trim($param['appid']))){
            return Normal::returnCode(Normal::FAIL,"缺少参数appid");
        }
        if(empty(trim($param['secret']))){
            return Normal::returnCode(Normal::FAIL,"缺少参数secret");
        }
        if(empty(trim($param['order_url']))){
            return Normal::returnCode(Normal::FAIL,"缺少参数order_url");
        }
        $add_data['account']=$param['mobile'];
        $add_data['business_name']=$param['business_name'];
        $add_data['cd']=time();
        $add_data['md']=time();
        $add_data['status']=1;
        $args = [
            'mobile'   => $param['mobile'],
        ];
        $checkMember = callTcpService('bbcUserAccountRegister',$args);
        if($checkMember['code']==200){
            $mid=$checkMember['data']['mid'];
        }else{
            return Normal::returnCode(Normal::FAIL,"SSO服务错误:".$checkMember['msg']);
        }
        Db::startTrans();
        try{
            $cid=Channel::instance()->add($add_data);
            $group['name']="超级管理员";
            $group['is_root']=1;
            $group['status']=1;
            $group['cd']=time();
            $group['cid']=$cid;
            $group_id=AuthGroup::instance()->add($group);
            $manager_data['cid']=$cid;
            $manager_data['mid']=$mid;
            $manager_data['account']=trim($param['account']);
            $manager_data['password']=md5(trim($param['pass']));
            $manager_data['name']=trim($param['name']);
            $manager_data['status']=1;
            $manager_data['group_id']=$group_id;
            $manager_data['cd']=time();
            $manager_data['md']=time();
            Manager::instance()->add($manager_data);
            ChannelWx::instance()->add(
                ['cid'=>$cid,'stb_app_id'=>trim($param['appid']),'stb_app_secret'=>trim($param['secret']),'stb_url'=>trim($param['order_url'])]
            );
            if($cid){
                Db::commit();
                return Normal::returnCode(Normal::SUC,"创建成功",['cid'=>$cid, 'notify_url'=>$add_data['notify_url'].$cid]);
            }else{
                Db::rollback();
                return Normal::returnCode(Normal::FAIL,"创建失败");
            }
        }catch (\Exception $e) {
            Db::rollback();
            return Normal::returnCode(Normal::FAIL,$e->getMessage());
        }
    }

    /**
     * 修改大B账号密码
     * @param array $param
     * @return array
     */
    public function changeChannelPass(array $param )
    {
        if(empty($param['cid'])){
            return Normal::returnCode(Normal::FAIL,"缺少参数大b的id");
        }
        $channel=Channel::instance()->info(['id'=>$param['cid']]);
        if(empty($channel)){
            return Normal::returnCode(Normal::FAIL,"所选大B不存在");
        }
        if(empty($param['account'])){
            return Normal::returnCode(Normal::FAIL,"请输入修改密码的账号");
        }
        if(empty($param['pass'])){
            return Normal::returnCode(Normal::FAIL,"请输入新的密码");
        }
        $manager=Manager::instance()->info(['cid'=>$param['cid'],'account'=>$param['account']]);
        if(empty($manager)){
            return Normal::returnCode(Normal::FAIL,"该账号不存在");
        }
        Manager::instance()->edit(['id'=>$manager['id']],['password'=>md5($param['pass']),'md'=>time()]);
        return Normal::returnCode(Normal::SUC,"操作成功");

    }

    /**
     * 大B列表
     * @return array
     */
    public function channelList()
    {
        $list=Channel::instance()->lists(['_order_'=>'id desc','_fields_'=>'id,business_name']);
        return Normal::returnCode(Normal::SUC,"请求成功",$list);
    }


    /**
     * 新建编辑服务商等级
     * @param array $param
     * @return array
     */
    public function serviceProviderLevel( array $param )
    {
        if(empty($param['level'])){
            return Normal::returnCode(Normal::FAIL,"请输入服务商等级");
        }
        if(!is_numeric($param['level'])){
            return Normal::returnCode(Normal::FAIL,"服务商等级需要输入数字");
        }
        $has=ServiceLevel::instance()->info(['level'=>$param['level']]);
        if($has){
            if((!empty($param['id']) && $has['id']<>$param['id']) || empty($param['id'])){
                return Normal::returnCode(Normal::FAIL,"等级".$param['level'].'已存在');
            }
        }
        if(empty($param['level_name'])){
            return Normal::returnCode(Normal::FAIL,"请输入等级名称");
        }
        if(!empty($param['id'])){
            $old=ServiceLevel::instance()->info(['id'=>$param['id']]);
            if(empty($old)){
                return Normal::returnCode(Normal::FAIL,"编辑的服务商等级不存在");
            }else{
                $res=ServiceLevel::instance()->edit(['id'=>$old['id']],['level'=>$param['level'],'level_name'=>$param['level_name'],'content'=>$param['content'],'md'=>time()]);
                if($res){
                    return Normal::returnCode(Normal::SUC,"编辑成功");
                }else{
                    return Normal::returnCode(Normal::FAIL,"编辑失败");
                }
            }
        }else{
            $res=ServiceLevel::instance()->add(['level'=>$param['level'],'level_name'=>$param['level_name'],'content'=>$param['content'],'md'=>time()]);
            if($res){
                return Normal::returnCode(Normal::SUC,"新增成功");
            }else{
                return Normal::returnCode(Normal::FAIL,"新增失败");
            }
        }
    }

    /**
     * 服务商等级列表
     * @return array
     */
    public function serviceProviderLevelList()
    {
        $list=ServiceLevel::instance()->lists(['_order_'=>'level asc']);
        return Normal::returnCode(Normal::SUC,"请求成功",$list);
    }

    /**
     * 服务商等级详情
     * @param array $param
     * @return array
     */
    public function serviceProviderLevelDetail(array $param)
    {
        if(empty($param['id'])){
            return Normal::returnCode(Normal::FAIL,"缺少参数id");
        }
        $info=ServiceLevel::instance()->info(['id'=>$param['id']]);
        if(empty($info)){
            return Normal::returnCode(Normal::FAIL,"等级不存在");
        }else{
            return Normal::returnCode(Normal::SUC,"请求成功",$info);
        }

    }

    /**
     * 新增编辑服务商
     * @param array $param
     * @return array
     */
    public function serviceProvider(array $param)
    {
        if(empty($param['id'])){
            if(empty($param['cid'])){
                return Normal::returnCode(Normal::FAIL,"请选择服务商所属大B");
            }
            $channel=Channel::instance()->info(['id'=>$param['cid']]);
            if(empty($channel)){
                return Normal::returnCode(Normal::FAIL,"所选大B不存在");
            }
        }
        if(empty($param['name'])){
            return Normal::returnCode(Normal::FAIL,"请输入服务商名称");
        }
        $hasName=ServiceProvider::instance()->info(['name'=>$param['name'],'cid'=>$param['cid']]);
        if(empty($param['level_id'])){
            return Normal::returnCode(Normal::FAIL,"请选择服务商等级");
        }
        $level=ServiceLevel::instance()->info(['id'=>$param['level_id']]);
        if(empty($level)){
            return Normal::returnCode(Normal::FAIL,"所选服务商等级不存在");
        }
        if(empty($param['mobile'])){
            return Normal::returnCode(Normal::FAIL,"请输入联系方式");
        }
        $hasMobile=ServiceProvider::instance()->info(['mobile'=>$param['mobile'],'cid'=>$param['cid']]);
        if(!empty($param['id'])){
            if($hasName && $hasName['id']<>$param['id']){
                return Normal::returnCode(Normal::FAIL,"服务商名称已存在");
            }
            if($hasMobile && $hasMobile['id']<>$param['id']){
                return Normal::returnCode(Normal::FAIL,"联系方式已存在");
            }
        }else{
            if($hasMobile){
                return Normal::returnCode(Normal::FAIL,"联系方式已存在");
            }
            if($hasName){
                return Normal::returnCode(Normal::FAIL,"服务商名称已存在");
            }
        }
        $param['status']=$param['status']??0;
        $data=[
           'cid'      => $param['cid'],
           'name'     => $param['name'],
           'level_id' => $param['level_id'],
           'mobile'   => $param['mobile'],
           'status'   => $param['status'],
            'recommend_name'    => $param['recommend_name']??'',
            'recommend_idcard'  => $param['recommend_idcard']??'',
           'md'       => time()
        ];
        if(!empty($param['id'])){
            $info=ServiceProvider::instance()->info(['id'=>$param['id']]);
            if(empty($info)){
                return Normal::returnCode(Normal::FAIL,"编辑的服务商不存在");
            }else{
                unset($data['cid']);
                $res=ServiceProvider::instance()->edit(['id'=>$info['id']],$data);
                if($res){
                    return Normal::returnCode(Normal::SUC,"编辑成功");
                }else{
                    return Normal::returnCode(Normal::FAIL,"编辑失败");
                }
            }
        }else{
            $res=ServiceProvider::instance()->add($data);
            if($res){
                return Normal::returnCode(Normal::SUC,"新增成功",$res);
            }else{
                return Normal::returnCode(Normal::FAIL,"新增失败");
            }
        }
    }

    /**
     * 服务商列表
     * @param array $param
     * @return array
     */
    public function serviceProviderList(array $param)
    {
        $page=$param['page']??1;
        $limit=$param['limit']??10;
        $where=[
            '_fields_'=>'id,cid,name,level_id,status,mobile,recommend_name,recommend_idcard',
            '_order_'=>'id desc'
        ];
        if(!empty($param['id'])){
            $where[]=['id','=',$param['id']];
        }        
        if(!empty($param['name'])){
            $where[]=['name','like','%'.$param['name'].'%'];
        }
        if(!empty($param['level_id'])){
            $where[]=['level_id','=',$param['level_id']];
        }
        if(!empty($param['cid'])){
            $where[]=['cid','=',$param['cid']];
        }
        if(isset($param['status']) && $param['status']!==''){
            $where[]=['status','=',$param['status']];
        }
        if(!empty($param['mobile'])){
            $where[]=['mobile','like','%'.$param['mobile'].'%'];
        }
        $list=ServiceProvider::instance()->listPages($where,$limit,$page);
        $num=ServiceProvider::instance()->countNum($where);
        $level=ServiceLevel::instance()->lists(['_fields_'=>'id,level_name']);
        $level=array_column($level,'level_name','id');
        $channel=Channel::instance()->lists(['_fields_'=>'id,business_name']);
        $channel=array_column($channel,'business_name','id');
        foreach ($list as $k=>$v){
            $list[$k]['channel_name']=$channel[$v['cid']];
            $list[$k]['level_name']=$level[$v['level_id']];
            $list[$k]['status_name']=$v['status']==1?'启用':'禁用';
            $list[$k]['business_number']=ChannelBusiness::instance()->countNum(['sp_id'=>$v['id']]);
            $order=Order::instance()->lists(['sp_id'=>$v['id'],'pay_status'=>1,'_fields_'=>'price_order']);
            $list[$k]['order_number']=count($order);
            $list[$k]['order_money']=array_sum(array_column($order,'price_order'));
        }
        $data['total']=$num;
        $data['list']=$list;
        return Normal::returnCode(Normal::SUC,"请求成功",$data);
    }


    /**
     * 服务商列表下拉菜单
     * @param array $param
     * @return array
     */
    public function serviceProviderSelectList(array $param)
    {
        $where=[
            '_fields_'=>'id,name,mobile',
            '_order_'=>'id desc'
        ];
        if(!empty($param['cid'])){
            $where[]=['cid','=',$param['cid']];
        }
        
        if(!empty($param['id'])){
            $where[]=['id','=',$param['id']];
        }
        $list=ServiceProvider::instance()->lists($where);
        return Normal::returnCode(Normal::SUC,"请求成功",$list);
    }

    /**
     * 大B商品列表
     * @param array $param
     * @return array
     */
    public function channelGoodsList(array $param)
    {
        if(empty($param['cid'])){
            return Normal::returnCode(Normal::FAIL,"缺少参数大Bid:cid");
        }
        $page=$param['page']??1;
        $limit=$param['limit']??10;
        $where=[
            ['cid','=',$param['cid']],
            ['df','=',0],
            '_order_'=>'id desc',
            '_fields_'=>'id,skucode,name,barcode,is_bonded,class_id,brand_id,origin'
        ];
        if(!empty($param['name'])){
            $where[]=['name','like','%'.$param['name'].'%'];
        }
        if(!empty($param['origin'])){
            $where[]=['origin','like','%'.$param['origin'].'%'];
        }
        if(!empty($param['skucode'])){
            $where[]=['skucode','like','%'.$param['skucode'].'%'];
        }
        if(!empty($param['barcode'])){
            $where[]=['barcode','like','%'.$param['barcode'].'%'];
        }
        if(isset($param['goodsType']) && $param['goodsType']!==''){
            $where[]=['is_bonded','=',$param['goodsType']];
        }
        if(!empty($param['class_id'])){
            $children = GoodsClass::instance()->where('pid', $param['class_id'])->where('df', 0)->where('show', 1)->column('id');
            if (!empty($children)) {
                $th = GoodsClass::instance()->where('pid', 'in', $children)->where('df', 0)->where('show', 1)->column('id');
                $children = array_merge($children, $th);
            }
            array_push($children, $param['class_id']);
            $where[]=['class_id','in',$children];
        }
        if(!empty($param['brand_id'])){
            $where[]=['brand_id','=',$param['brand_id']];
        }
        if(isset($param['except_goods']) && !empty($param['except_goods'])){
            $where[]=['id','NOT IN',$param['except_goods']];
        }
        $list=Goods::instance()->listPages($where,$limit,$page);
        $num=Goods::instance()->countNum($where);
        $data['total']=$num;
        $class=GoodsClass::instance()->lists(['cid'=>$param['cid'],'_fields_'=>'id,name']);
        $class=array_column($class,'name','id');
        $brand=GoodsBrand::instance()->lists(['cid'=>$param['cid'],'_fields_'=>'id,name']);
        $brand=array_column($brand,'name','id');
        foreach ($list as $k=>$v){
            $list[$k]['class_name']=$class[$v['class_id']]??'';
            $list[$k]['brand_name']=$brand[$v['brand_id']]??'';
            $list[$k]['is_bonded']=Goods::instance()->is_bonded[$v['is_bonded']];
        }
        $data['list']=$list;
        return Normal::returnCode(Normal::SUC,"操作成功",$data);
    }


    /**
     * @获取商品分类
     * @param    array $param
     * @access   public
     * @return   array
     */
    public function getClass(array $param = []):array
    {
        if(empty($param['cid'])){
            return Normal::returnCode(Normal::FAIL,"缺少参数大Bid:cid");
        }
        $where = [
            'show'      => 1,
            'df'        => 0,
            'cid'       =>$param['cid']??0,
            '_fields_'  => [
                'id', 'name', 'icon', 'pid'
            ],
            '_order_'=> ['sort'=>'desc']
        ];
        $classes = GoodsClass::instance()->lists($where);
        $classes = tree($classes, 0, 'id', 'pid');
        $classes = array_map(function($item){
            return [
                'id'    => $item['id'],
                'name'  => $item['name'],
                'icon'  => $item['icon'],
                'pid'   => $item['pid'],
                'son'   => empty($item['son'])?[]:$item['son'],
            ];
        }, $classes);
        return Normal::returnCode(Normal::SUC,"操作成功",$classes);
    }

    /**
     * @获取商品品牌
     * @param    array $param
     * @access   public
     * @return   array
     */
    public function getBrand(array $param = []):array
    {
        if(empty($param['cid'])){
            return Normal::returnCode(Normal::FAIL,"缺少参数大Bid:cid");
        }
        $list=GoodsBrand::instance()->lists(['cid'=>$param['cid'],'_fields_'=>'id,name']);
        return Normal::returnCode(Normal::SUC,"操作成功",$list);
    }



}

